package de.baumann.browser.activitys.oc

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import de.baumann.browser.R
import de.baumann.browser.base.BaseOdinActivity
import de.baumann.browser.db.ETHWallet
import de.baumann.browser.iview.ILoginView
import de.baumann.browser.present.LoginPresenter
import de.baumann.browser.utils.StringUtil
import de.baumann.browser.utils.saveMoneyAddress
import de.baumann.browser.utils.saveWalletName
import de.baumann.browser.utils.web3j.ETHWalletUtils
import de.baumann.browser.utils.web3j.WalletDaoUtils
import de.baumann.browser.views.dialog.PayPwdDialog
import de.baumann.browser.views.dialog.RemoveWalletDialog
import de.baumann.browser.views.dialog.UpdateWalletNameDialog
import de.baumann.browser.views.dialog.WalletPasswordDailog
import kotlinx.android.synthetic.main.activity_oc_wallet_setting.*
import kotlinx.android.synthetic.main.include_tool_bar.*


class OcWalletSettingActivity : BaseOdinActivity<ILoginView, LoginPresenter>(), ILoginView {

    companion object {
        fun startOcWalletSettingActivityForResult(context: Activity, odinWallet: ETHWallet) {
            context.startActivityForResult(Intent(context, OcWalletSettingActivity::class.java).apply {
                val bundel = Bundle().apply {
                    putSerializable("odinWallet", odinWallet)
                }
                putExtras(bundel)
            }, 9999)
        }
    }

    override fun getLayout(): Int {
        return R.layout.activity_oc_wallet_setting
    }

    override fun getTitleText(): String {
        return "钱包设置"
    }

    override fun initView() {
        initToolbar(commToolBar, commTitle)

        tvOdinWalletAddress.setOnClickListener {
            StringUtil.copy(mContext, tvOdinWalletAddress.text.toString().trim())
            showShortToast("已复制到剪切板")
        }

        llWalletName.setOnClickListener {
            UpdateWalletNameDialog(mContext, object : UpdateWalletNameDialog.Callback {
                override fun callback(name: String) {
                    twdWalletname.text = name
                    WalletDaoUtils.updateWalletName(getWallet().id, name)
                }
            }).show()
        }

        tvExportPrivateKey.setOnClickListener {
            WalletPasswordDailog(mContext, object : WalletPasswordDailog.Callback {
                override fun password(password: String) {
                    showLoading()
                    try {
                        val privaeKey = ETHWalletUtils.derivePrivateKey(getWallet().id, password)
                        OcPrivateKeyActivity.startOcPrivateKeyActivity(mContext, privaeKey)
                        hideLoading()
                    } catch (e: Exception) {
                        hideLoading()
                        e.printStackTrace()
                        if ("Invalid password provided" == e.message) {
                            Toast.makeText(mContext, "密码错误", Toast.LENGTH_SHORT).show()
                        } else {
                            Toast.makeText(mContext, "私钥导出失败", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            }).show()
        }

        tvExportKeyStore.setOnClickListener {
            WalletPasswordDailog(mContext, object : WalletPasswordDailog.Callback {
                override fun password(password: String) {
                    showLoading()
                    try {
                        val keystore = ETHWalletUtils.deriveKeystore(getWallet().id, password)
                        OcKeystoreActivity.startOcPrivateKeyActivity(mContext, keystore)
                        hideLoading()
                    } catch (e: Exception) {
                        hideLoading()
                        e.printStackTrace()
                        if ("Invalid password provided" == e.message) {
                            Toast.makeText(mContext, "密码错误", Toast.LENGTH_SHORT).show()
                        } else {
                            Toast.makeText(mContext, "Keystore导出失败", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            }).show()
        }

        btnRemoveWallet.setOnClickListener {
            RemoveWalletDialog(mContext, object : RemoveWalletDialog.RemoveCallback {
                override fun remove() {
                    val loadAll = WalletDaoUtils.loadAll()
                    pwdd = PayPwdDialog(mContext, object : PayPwdDialog.PwdCallback {
                        override fun callback(pwd: String) {
                            try {
                                pwdd!!.dismiss()
                                Log.d("paw", "callback:1111 " + +loadAll.size)

                                if (WalletDaoUtils.loadAll().size > 1) {
                                    Log.d("paw", "callback:111100000 " + +loadAll.size)
                                    ETHWalletUtils.deriveKeystore(getWallet().id, pwd)
                                    ETHWalletUtils.deleteWallet(getWallet().id)
                                    saveMoneyAddress(WalletDaoUtils.loadAll()[0].address)
                                    saveWalletName(WalletDaoUtils.loadAll()[0].name)
//                                    setResult(Activity.RESULT_OK)
                                    finish()
                                } else {
                                    Log.d("paw", "callback:111122222 " + +loadAll.size)
                                    ETHWalletUtils.deriveKeystore(getWallet().id, pwd)
                                    ETHWalletUtils.deleteWallet(getWallet().id)
                                    saveMoneyAddress("")
                                    saveWalletName("")
                                    finish()
                                }


                            } catch (e: Exception) {
                                e.printStackTrace()
                                if ("Invalid password provided" == e.message) {
                                    Toast.makeText(mContext, "密码错误", Toast.LENGTH_SHORT).show()
                                } else {
                                    Log.d("paw", "callback:3333${e.toString()}")
                                    Toast.makeText(mContext, "移除失败", Toast.LENGTH_SHORT).show()
                                }
                            }
                        }
                    })
                    pwdd!!.show()
                }
            }).show()
        }
    }

    private var pwdd: PayPwdDialog? = null

    override fun initData() {
        val wallet = getWallet()
        var address = wallet.address
        if (address.startsWith("0")) {
            address = "od${address.substring(1)}"
        }
        tvOdinWalletAddress.text = address
        twdWalletname.text = wallet.name
    }


    private fun getWallet(): ETHWallet {
        return intent.getSerializableExtra("odinWallet") as ETHWallet
//        return getETHWallet()
    }

    override fun showBindEth(): Boolean {
        return false
    }

    override fun getAccount(): String {
        return WalletDaoUtils.loadAll()[0].address
    }

    override fun getPassword(): String {
        return ""
    }

    override fun loginSuccess(loginName: String, licenceStatus: Int) {
        finish()
    }

    override fun createPresenter(): LoginPresenter {
        return LoginPresenter()
    }

    override fun createView(): ILoginView {
        return this
    }
}
